<template>
    <div class="cont">
        <nav-bar title="朋友圈发单" rightImg="https://h5.dhcc.wang/newprogram/wxRobot/nav_refresh_black.png" :bgStyle="bgStyle"
            text-color="#333333" :rotate.sync="reload" @leftClick="back" @rightClick="refresh" />
        <div class="flex align-center p-tb-12 justify-between m-l-10 m-r-10 m-t-10 radius8 box-shadow-new">
            <div class="m-l-10 text-bold">是否开启跟发朋友圈功能</div>
            <van-switch class="m-r-10" size="20" v-model="followOn" :active-color="config.mac_assist_color"
                @change="switchChange" />
        </div>
        <div v-if="followOn">
            <div class="radius8 m-l-10 m-r-10 m-t-10 p-10 box-shadow-new">
                <div class="flex justify-between">
                    <div class="flex align-center">
                        <span class="m-r-5 font-14 text-bold">朋友圈屏蔽标签组</span>
                        <van-popover class="friends-popover" v-model="showPopover" trigger="click" :offset="[40,8]">
                            <div class="font-12 color-9 popover-content">可设置需屏蔽的好友分组，对方将无法看到您跟发的朋友圈，若分组好友有更新，需手动点击刷新同步后方可生效</div>
                            <template #reference>
                                <van-icon name="question-o" class="m-t-4 color-9"/>
                            </template>
                        </van-popover>

                    </div>
                    <div class="flex align-center" @click="syncList">
                        <span class="m-r-5 font-12 color-9">刷新同步</span>
                        <img width="20" :class="listRefresh ? 'rotate' : ''" src="@/assets/img/refresh-icon-gray.png">
                    </div>
                </div>
                <div>
                    <div class="m-t-10" v-if="tagGroup && tagGroup.length > 0"><van-tag v-for="(opt, i) in tagGroup"
                            :key="i" v-if="i<6" class="m-r-10 m-b-10 p-tb-5 p-lr-8" closeable @close="delTag(opt,2)" color="#e5f9f1" text-color="#07c160">
                            <div class="tag van-ellipsis">{{ opt.labelName }}</div>
                        </van-tag></div>
                    <div v-else>
                        <div class="flex justify-center">
                            <div class="font-13 m-t-20 m-b-10 p-lr-20 p-tb-5 color-white radius40 flex align-center text-bold"
                                :style="`background:${config.mac_assist_color}`" @click="selectTag(1)"><van-icon class="m-r-5"
                            name="add-o" />选择要屏蔽的标签组</div>
                        </div>
                        <div class="font-12 color-9 text-center m-b-10">可设置需屏蔽的好友分组，对方将无法看到您跟发的朋友圈<br />若分组好友有更新，需手动点击刷新同步后方可生效
                        </div>
                    </div>
                    <div class="flex justify-between van-hairline--top p-tb-12 p-lr-12 p-b-0"
                    v-if="tagGroup && tagGroup.length > 0">
                    <div class="flex align-center color-9" @click="selectTag(1)"><van-icon class="m-r-5"
                            name="add-o" />选择标签组
                    </div>
                    <div class="flex align-center m-l-20 color-9" @click="selectTag(2)">
                        <van-icon class="m-r-5" size="18" name="eye-o" />查看全部
                    </div>


                </div>
                </div>
            </div>
            <div class="radius8 m-l-10 m-r-10 m-t-10 p-10 box-shadow-new">
                <div class="flex align-center">
                    <span class="m-r-5 font-14 text-bold">朋友圈关键词屏蔽管理</span>
                    <van-popover v-model="keywordPopover" trigger="click">
                        <div class="font-12 color-9 p-10">可配置屏蔽词，包含该屏蔽词的朋友圈内容将不会跟发</div>
                        <template #reference>
                            <van-icon name="question-o" class="m-t-4 color-9"/>
                        </template>
                    </van-popover>
                </div>
                <div>
                    <div class="m-t-10" v-if="tagKeyword && tagKeyword.length > 0">
                        <van-tag v-for="(opt, i) in tagKeyword" :key="i" class="m-r-10 m-b-10 p-tb-5 p-lr-8"
                            color="#e5f9f1" text-color="#07c160" closeable @close="delTag(opt,3)">
                            <div class="tag van-ellipsis">{{ opt }}</div>
                        </van-tag>
                    </div>
                    <div v-else>
                        <div class="flex justify-center">
                            <div class="font-13 m-t-20 m-b-10 p-lr-20 p-tb-5 color-white radius40 flex align-center text-bold"
                                :style="`background:${config.mac_assist_color}`" @click="addKeyword"><van-icon class="m-r-5"
                            name="add-o" /> 添加屏蔽词</div>
                        </div>
                        <div class="font-12 color-9 text-center m-b-10">支持添加多个屏蔽词<br />包含该屏蔽词的朋友圈内容将不会跟发</div>
                    </div>
                </div>
                <div class="flex justify-between van-hairline--top p-tb-12 p-lr-12 p-b-0"
                    v-if="tagKeyword && tagKeyword.length > 0">
                    <div class="flex align-center color-9" @click="addKeyword"><van-icon class="m-r-5"
                            name="add-o" />添加屏蔽词
                    </div>
                    <div class="flex align-center m-l-20 color-9" @click="selectTag(3)">
                        <van-icon class="m-r-5" size="18" name="eye-o" />查看全部
                    </div>


                </div>
            </div>
        </div>
        <div class="m-l-10 m-r-10 m-t-20 font-14 text-bold">选择要跟发的朋友圈</div>
        <van-list v-if="list && list.length > 0" :finished="finished" finished-text="没有更多了" @load="onLoadMore">
            <div class="radius8 m-l-10 m-r-10 m-t-10 p-10 item box-shadow-new"
                :class="item.user_name == userName ? 'item-active' : ''" v-for="(item, index) in list" :key="index">

                <div class="flex align-center">
                    <img class="avatar" :src="item.group_avatar || item.small_head_img_url" alt="">
                    <div class="m-l-10">
                        <div class="flex align-center">
                            <div class="text-bold van-ellipsis flex align-center"
                                :class="item.latest_msg_time ? 'title' : 'title-max'">{{ item.group_name || item.nick_name
                                }} <img src="https://img.huajuanyun.com/utools/2023/126/1701846235866.png" width="18"
                                    v-if="item.group_name.indexOf('视频') != -1" class="m-l-5"></div>
                            <div class="color-9 text-12 font-12" v-if="item.latest_msg_time">{{ item.latest_msg_time * 1000
                                | getDateDiff }}</div>
                        </div>
                        <div class="van-multi-ellipsis--l2 color-9 font-12 m-t-5 title-max">{{ item.desc }}</div>
                    </div>

                </div>
                <div class="flex justify-between m-t-15">
                    <div class="font-12 btn m-r-10" @click="openPage('/friendsDetail', { username: item.user_name })">
                        <van-icon name="eye" style="top:2px" /> 预览朋友圈
                    </div>
                    <div class="font-12 btn btn-org" :class="item.user_name == userName ? 'btn-forbid' : ''"
                        @click="following(item, index)">
                        <van-icon class="m-r-5" name="checked" style="top:2px" />{{ item.user_name == userName ? '已绑定' :
                            '绑定跟发' }}
                    </div>
                </div>
                <div v-if="item.user_name == userName">
                    <van-icon name="success" size="22" class="active-icon" />
                </div>
            </div>
        </van-list>
        <noData v-else text="暂无数据" />
        <!-- 添加屏蔽关键词 -->
        <blockKeywords v-if="addShow" :popup-visible="addShow" :list="list" @close="keywordClose" @ok="selectOk" />
        <!-- 选择/查看标签组 查看关键词列表 -->
        <blockKeywordsList v-if="listShow" :popup-visible="listShow" :list="listType==1?tagList:listType==2?tagGroup:tagKeyword" :type="listType" @ok="selectOk" @close="listClose" />
    </div>
</template>

<script>
import { List, Switch, Radio, RadioGroup, Cell, CellGroup, Image, Notify, Tag, Popover } from 'vant'
import blockKeywords from '@/components/blockKeywords.vue'
import blockKeywordsList from '@/components/blockKeywordsList.vue'
export default {
    components: {
        [List.name]: List,
        [Switch.name]: Switch,
        [RadioGroup.name]: RadioGroup,
        [Radio.name]: Radio,
        [CellGroup.name]: CellGroup,
        [Cell.name]: Cell,
        [Image.name]: Image,
        [Notify.name]: Notify,
        [Tag.name]: Tag,
        [Popover.name]: Popover,
        blockKeywords,
        blockKeywordsList
    },
    data () {
        return {
            bgStyle: '#fff',
            list: [],
            page: 1,
            pagesize: 30,
            reload: true,
            loading: true,
            result: '',
            finished: false, // 控制在页面往下移动到底部时是否调用接口获取数据
            isUpLoading: false, // 上拉加载
            config: {},
            followOn: false,
            bgBtnStyle: '#fff',
            userName: '',
            showPopover: false,
            tagGroup: [],
            keywordPopover: false,
            addShow: false,
            tagKeyword: [],
            listRefresh: false,
            tagList: [],
            listShow: false,
            listType: 1,
            isFirst: true
        }
    },
    mounted () {
        this.config = this.$DB.get('robotCfg')
        this.bgBtnStyle = `linear-gradient(90deg, ${this.config.mac_main_color} 0%, ${this.config.mac_assist_color} 100%)`
        this.init()
        this.setHeader()
        this.getList(true)
    },
    methods: {
        init () {
            this.$api.getContactDetail({ username: this.config.device_info.bind_wechat }, true).then(async res => {
                if (res.code != 1) {
                    this.$dialog.alert({
                        title: '温馨提示',
                        message: res.msg
                    }).then(() => {
                        this.back()
                    })
                    return
                }
                this.followOn = res.data.status == 1
                this.userName = res.data.user_name_source || ''
                if (this.followOn) {
                    this.getConfig()
                }
            }).finally(() => {
                setTimeout(() => {
                    this.reload = false
                }, 500)
            })
        },
        getConfig () {
            this.$api.getSnsConfig({}, true).then(res => {
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
                this.isFirst = false
                this.tagList = res.data.label_list
                if (res.data.sns_block_label_idlist) {
                    let arr = res.data.sns_block_label_idlist.split(',')
                    arr.forEach(item => {
                        let index = res.data.label_list.findIndex(opt => opt.labelId == item)
                        if (index != -1) {
                            this.tagGroup.push(res.data.label_list[index])
                            this.tagList[index].isChecked = true
                        }
                    })
                }
                if (res.data.sns_block_keywords) {
                    this.tagKeyword = res.data.sns_block_keywords.split(',')
                }
            })
        },
        getList (first) {
            if (first) {
                this.page = 1
                this.list = []
            }
            this.$api.getListSourceSns({ page: this.page, pagesize: this.pagesize }, true).then(async res => {
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
                this.list = [...this.list, ...res.data.list]
                this.page++
                this.loading = false
                if (this.list.length == res.data.total) {
                    this.finished = true
                }
            }).finally(() => {
                setTimeout(() => {
                    this.reload = false
                }, 300)
            })
        },
        onLoadMore () {
            if (!this.finished && !this.loading) {
                this.loading = true
                this.getList()
            }
        },
        refresh () {
            this.reload = true
            this.getList(true)
        },
        openPage (url, item = {}) {
            this.$router.push({
                path: url,
                query: item
            })
        },
        back () {
            this.$router.go(-1)
        },
        setHeader () {
            this.$common.setHeader({
                native_headershow: 0,
                topstyle: 'topcolor',
                native_top_words_color: '#ffffff',
                str_link_color: '#ffffff',
                end_link_color: '#ffffff'
            })
        },
        switchChange (e) {
            if (!this.userName) {
                this.followOn = !e
                return this.$toast('请先绑定一个源头群')
            }
            this.$api.snsStatus({ status: e ? 1 : 0 }).then(res => {
                if (res.code != 1) {
                    this.followOn = !e
                    return this.$toast(res.msg)
                }
                this.followOn = e
                if (this.followOn && this.isFirst) {
                    this.getConfig()
                }
                this.$toast('设置成功')
            })
        },
        // 开始跟圈
        following (item, index) {
            if (this.userName == item.user_name) {
                return this.$toast('已绑定无需操作')
            }
            this.$dialog.confirm({
                title: '提示',
                message: `确认绑定跟发“${item.group_name || item.nick_name}”朋友圈？`
            }).then(() => {
                this.$api.updateSns({ username_source: item.user_name }, true).then(async res => {
                    if (res.code != 1) {
                        return this.$toast(res.msg)
                    }
                    this.userName = item.user_name
                    Notify({
                        type: 'success',
                        message: '绑定成功^_^',
                        duration: '800'
                    })
                    this.$common.setHeader({
                        str_link_color: '#07c160',
                        end_link_color: '#07c160'
                    })
                    setTimeout(() => {
                        this.setHeader()
                    }, 1000)
                })
            })
        },
        // 同步通讯录
        syncList () {
            this.listRefresh = true
            this.$api.syncContact({}).then(async res => {
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
                this.getList()
            }).finally(() => {
                setTimeout(() => {
                    this.$toast('同步请求已发送\n请稍后重新查看\n刷新同步2分钟内最多一次')
                    this.listRefresh = false
                }, 300)
            })
        },
        // 删除
        delTag (item, type) {
            this.listType = type
            let obj = {}
            if (type == 2) {
                obj = {
                    ...item,
                    type: 'del'
                }
            } else {
                obj = {
                    labelName: item,
                    type: 'del'
                }
            }
            this.selectOk(obj)
        },
        selectTag (type) {
            this.listShow = true
            this.listType = type
        },
        addKeyword () {
            this.listType = 4
            this.addShow = true
        },
        selectOk (item) {
            let httpUrl = null
            let arr1 = this.$common.deepClone(this.tagGroup)
            let arr2 = this.$common.deepClone(this.tagKeyword)
            let index = null
            if (item.type == 'add') {
                if (this.listType == 1) {
                    arr1.push(item)
                } else {
                    let index1 = arr2.findIndex(opt => item.labelName == opt)
                    if (index1 != -1) {
                        return this.$toast('这个关键词已经添加过了')
                    }
                    arr2.push(item.labelName)
                    this.keywordClose()
                }
            } else {
                if (this.listType == 2) {
                    index = arr1.findIndex(opt => item.labelId == opt.labelId)
                    arr1.splice(index, 1)
                } else {
                    index = arr2.findIndex(opt => item.labelName == opt)
                    arr2.splice(index, 1)
                }
            }
            if (this.listType == 3 || this.listType == 4) {
                httpUrl = this.$api.updateBlockKeywords({
                    block_keywords: arr2.join()
                })
            } else {
                httpUrl = this.$api.updateSnsBlockLabelId({
                    block_label_id: arr1.map(opt => opt.labelId).join()
                })
            }
            httpUrl.then(res => {
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
                this.tagGroup = arr1

                if (this.listType == 1) {
                    let index = this.tagList.findIndex(opt => item.labelId == opt.labelId)
                    this.tagList[index].isChecked = true
                } else if (this.listType == 2) {
                    let index = this.tagList.findIndex(opt => item.labelId == opt.labelId)
                    this.tagList[index].isChecked = null
                }

                this.tagKeyword = arr2
                this.$toast(item.type == 'add' ? '添加成功' : '删除成功')
            })
        },
        keywordClose () {
            this.addShow = false
        },
        listClose () {
            this.listShow = false
        }
    }
}
</script>
<style lang="less" scoped>
.cont {
    font-size: 14px;
    padding-top: 46px;

    .footer {
        position: fixed;
        bottom: 20px;
        left: 0;
        right: 0;
    }

    .title {
        max-width: 53vw;
    }

    .title-max {
        max-width: calc(100.0vw - 100px);
    }

    .avatar {
        width: 42px;
        height: 42px;
        flex: 0 0 42px;
        object-fit: cover;
        border-radius: 4px;
    }

    .btn {
        padding: 0 10px;
        color: #333333;
        border: 1px solid #dddddd;
        border-radius: 20px;
        height: 28px;
        line-height: 28px;
        width: calc(50vw);
        text-align: center;

        &-org {
            border: 1px solid #07c160;
            color: #07c160;
        }

        &-forbid {
            background: #07c160;
            border-color: #02b95a;
            color: #ffffff;
        }
    }

    .item {
        position: relative;

        .active-icon {
            position: absolute;
            right: 3px;
            top: 3px;
            // background: #07c160;
            color: #07c160;
            border-radius: 5px 0 8px 0;
            padding: 1px 4px;
        }
    }

    .item-active {
        background: #f7fff9 !important;
        color: #07c160;
        border: 1px solid #07c160;
    }
}
    .popover-content {
        max-width: 80vw;
        padding: 10px;
    }
    .tag {
            max-width: calc(33vw - 57px);
    }
</style>